<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <SelectButton v-if="buttonselectlist.length" :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-del="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              :disabled="row.enableStatus"
              @click="handleDelete(row.stordocNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:warehouseValue="{ row, item }">
          <template v-if="!row.index">
            {{ getWarehouse(row) }}
          </template>
        </template>
        <template v-slot:enableStatus="{ row, item }">
          <template v-if="!row.index">
            {{ (row[`${item.prop}`] === false ? '未启用' : row[`${item.prop}`] === true ? '已启用' : '——') || '——' }}
          </template>
        </template>
      </Table>
      <!-- <el-table
        ref="tableData"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="92%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column
          v-for="item, index in formDatalists"
          :key="index"
          :type="`${item.prop}`"
          :prop="`${item.prop}`"
          :label="item.name"
          min-width="200"
          :column-key="`${item.prop}`"
        >
          <template
            v-if="scope.row[`stordocNo`] !== undefined"
            slot-scope="scope"
          >
            <span
              v-if="item.prop === 'enableStatus'"
            >{{ (scope.row[`${item.prop}`] === false ? '未启用' : scope.row[`${item.prop}`] === true ? '已启用' : '——') || '——' }}</span>
            <span v-else>{{ scope.row[`${item.prop}`] || '——' }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="160" label="操作" fixed="right">
          <template v-if="scope.row.stordocNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              :disabled="scope.row.enableStatus"
              @click="handleDelete(scope.row.stordocNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            v-for="item,index in formDatalists"
            :key="index"
            :label="item.name + ':'"
            :prop="item.selectValue || item.prop"
            class="w50p"
            :rules="[
              { required: item.prop == 'address' ? addressRequired : item.required, message: item.name + '不能为空', trigger: item.type === 'input' ? 'blur' : 'change'}
            ]"
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="formData[ `${item.prop}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="formData[ `${item.selectValue}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items.name"
                :value="items.value"
              />
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.prop}`]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="'选择' + item.name"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import SelectButton from "@/components/selectbutton/index.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage";
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage";

export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot, SelectButton },
  mixins: [mymixin],
  data () {
    return {
      warehouseValue: '',
      buttonselectlist: [],
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: '仓库类型',
          prop: 'stordocType',
          type: 'select',
          options: [
            { name: "原料", value: "原料" },
            { name: "半成品", value: "半成品" },
            { name: "成品", value: "成品" }
          ],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '仓库名称',
          prop: 'stordocName',
          type: 'input',
        },
      ],
      selectedStaffList: [],
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "warehouseValue",
          selectValue: "warehouseValue",
          typeObj: {},
          name: "所属系统",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "stordocName",
          selectValue: "",
          typeObj: {},
          name: "仓库名称",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "address",
          selectValue: "",
          typeObj: {},
          name: "仓库地址",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "personName",
          selectValue: "personNo",
          typeObj: {},
          name: "负责人",
          required: false
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "phone",
          selectValue: "",
          typeObj: {},
          name: "电话号码",
          required: false,
          notSearch: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "stordocType",
          selectValue: "stordocType",
          typeObj: {
            list: [
              { name: "原料", value: "原料" },
              { name: "半成品", value: "半成品" },
              { name: "成品", value: "成品" }
            ]
          },
          name: "仓库类型",
          required: false
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "enableStatus",
          selectValue: "enableStatus",
          typeObj: {
            list: [
              { name: "未启用", value: false },
              { name: "已启用", value: true }
            ]
          },
          name: "启用状态",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remark",
          selectValue: "",
          typeObj: {},
          name: "备注",
          required: false,
          notSearch: true
        }
      ],
      rules: {
        stordocName: [
          { required: true, message: "请输入仓库名称", trigger: ["blur", "change"] },
        ],
        address: [
          { required: true, message: "请输入仓库地址", trigger: ["blur", "change"] },
        ],
        personNo: [
          { required: true, message: "请选择负责人", trigger: ["blur", "change"] },
        ],
        stordocType: [
          { required: true, message: "请选择仓库类型", trigger: ["blur", "change"] },
        ],
        enableStatus: [
          { required: true, message: "请选择启用状态", trigger: ["blur", "change"] },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: ["blur", "change"] },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1\d{10}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    }),
    addressRequired () {
      return !['entrust'].includes(this.formData.type)
    }
  },
  created () {
    let list = []
    this.formDatalists.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px'
      }
      if (['enableStatus', 'warehouseValue'].includes(el.prop)) {
        obj.slotName = el.prop
      }
      list.push(obj)
    })
    list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '150' })
    this.tableColumn = list

    this.queryWarehouseType()
    this.getPerson();
  },
  methods: {
    getWarehouse (data) {
      let row = this.buttonselectlist.find(el => { return el.warehouseValue == data.warehouseValue })
      return row ? row.warehouseName : ''
    },
    // 获取仓库类型
    queryWarehouseType () {
      warehouseApi.queryWarehouseType({}).then(res => {
        this.buttonselectlist = res.data.map(el => {
          return {
            ...el,
            name: el.warehouseName
          }
        })
        let index = this.formDatalists.findIndex(el => { return el.prop == 'warehouseValue' })
        if (index != -1) {
          this.$set(this.formDatalists[index].typeObj, 'list', res.data.map(el => {
          return {
            name: el.warehouseName,
            value: el.warehouseValue
          }
        }))
        }
        this.search();
      })
    },
    // 仓库类型切换
    batchstaumet (i) {
      this.warehouseValue = this.buttonselectlist[i].warehouseValue
      this.tableData = [];
      this.search();
    },
    // 获取记录人列表
    getPerson() {
      personApi.getStaffListByCondition().then(res => {
        if (res.code === 1) {
          let list = [];
          this.personList = res.data || [];
          res.data.forEach(item => {
            list.push({
              name: item.person.name,
              value: item.personNo
            });
          });
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "personName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    getTableDataList () {
      if (!this.warehouseValue) return
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchlist,
          warehouseValue: this.warehouseValue
        }
      };
      warehouseApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.stordocNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      warehouseApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          warehouseApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = {};
      this.nowChanceStau = "add";
      this.titleText = "添加仓库";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      this.nowChanceStau = "edit";
      this.titleText = "修改仓库";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      console.log(this.formData);
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let formData = { ...this.formData };
            warehouseApi.edit(formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let person = {
              ...this.formData,
              farming: sessionStorage.farming
            };
            warehouseApi.add(person).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .tab-select {
  width: 100%;
  .butt-list-sty {
    position: absolute;
    left: 5px;
    top: 7px;
  }
}
</style>
